package com.koron.sinoprobe.web.ledger.service.impl;

import com.koron.common.core.util.CodeTools;
import com.koron.sinoprobe.web.common.CommonUtils;
import com.koron.sinoprobe.web.ledger.bean.entity.SpContractRecord;
import com.koron.sinoprobe.web.ledger.mapper.SpContractRecordMapper;
import com.koron.sinoprobe.web.ledger.service.SpContractRecordService;
import org.koron.ebs.mybatis.SessionFactory;
import org.koron.ebs.mybatis.TaskAnnotation;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author twcao
 * @title: SpContractRecordServiceImpl
 * @projectName GDH_EAM_V2
 * @description: 专项项目付款记录service实现
 * @date 2021/12/617:03
 */
@Service
public class SpContractRecordServiceImpl implements SpContractRecordService {

    @Override
    @TaskAnnotation("queryById")
    public SpContractRecord queryById(SessionFactory factory, String id) {
        SpContractRecordMapper mapper = factory.getMapper(SpContractRecordMapper.class);
        return mapper.queryById(id);
    }

    @Override
    @TaskAnnotation("queryList")
    public List<SpContractRecord> queryList(SessionFactory factory, SpContractRecord query) {
        SpContractRecordMapper mapper = factory.getMapper(SpContractRecordMapper.class);
        return mapper.queryList(query);
    }

    @Override
    @TaskAnnotation("saveOrUpdate")
    public Integer saveOrUpdate(SessionFactory factory, List<SpContractRecord> list) {
        Assert.notEmpty(list, "记录不能为空");
        int row = 0;
        // 防止传进来的list是多个合同的合同记录
        list.stream().forEach(record -> deleteByContractId(factory, record.getContractId()));
        CommonUtils.sorted(list);
        for (SpContractRecord record : list) {
            Assert.hasText(record.getContractId(), "合同id不能为空");
            saveOrUpdate(factory, record);
            row++;
        }
        return row;
    }

    @Override
    public SpContractRecord saveOrUpdate(SessionFactory factory, SpContractRecord bean) {
        Assert.notNull(bean, "合同记录不能为空");
        bean.setId(StringUtils.isEmpty(bean.getId()) ? CodeTools.getCode32() : bean.getId());
        SpContractRecordMapper mapper = factory.getMapper(SpContractRecordMapper.class);
        mapper.saveOrUpdate(bean);
        return bean;
    }

    @Override
    @TaskAnnotation("deleteById")
    public Boolean deleteById(SessionFactory factory, String id) {
        SpContractRecordMapper mapper = factory.getMapper(SpContractRecordMapper.class);
        return mapper.deleteById(id) > 0;
    }

    @Override
    @TaskAnnotation("deleteByContractId")
    public int deleteByContractId(SessionFactory factory, String contractId) {
        SpContractRecordMapper mapper = factory.getMapper(SpContractRecordMapper.class);
        return mapper.deleteByContractId(contractId);
    }
}
